﻿using Message;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 注册面板
/// </summary>
public class RegisterView : ViewBase
{
    private Button registerButton;
    private Button backButton;

    private InputField nameInputField;
    private InputField pwdInputField;
    private InputField rePwdInputField;

    public override void Init(params object[] args)
    {
        base.Init(args);
        layer = PanelLayer.Panel;
    }

    public override void OnShowing()
    {
        base.OnShowing();
        Transform skinTrans = panelObj.transform;

        registerButton = skinTrans.Find("registerButton").GetComponent<Button>();
        backButton = skinTrans.Find("backButton").GetComponent<Button>();

        nameInputField = skinTrans.transform.Find("nameInputField").GetComponent<InputField>();
        pwdInputField = skinTrans.transform.Find("pwdInputField").GetComponent<InputField>();
        rePwdInputField = skinTrans.transform.Find("rePwdInputField").GetComponent<InputField>();

        registerButton.onClick.AddListener(OnRegister);
        backButton.onClick.AddListener(OnBack);

        NetMgr.Instance.OnConnect += OnConnect;
    }

    private void OnRegister()
    {
        //连接服务器
        if (NetMgr.Instance.state != State.Connected)
        {
            NetMgr.Instance.Connect();
            return;
        }
        else
        {
            Register();
        }
    }

    void OnConnect(State status)
    {
        Log.Debug("status:" + status.ToString());
        if (status == State.Connected)
        {
            Register();
        }
        if (status == State.TimeOut)
        {
            UIMgr.Instance.Show<TipView>("连接服务器超时!");
        }
        if (status == State.Error)
        {
            UIMgr.Instance.Show<TipView>("连接服务器出错!");
        }
    }

    void Register()
    {
        MsgMgr.Instance.AddListener(typeof(S2CRegisterRet), OnRegisterRet);
        //提交 
        C2SRegister ctsr = new C2SRegister();
        ctsr.uname = nameInputField.text;
        ctsr.pwd = Util.GetStringHash(pwdInputField.text);
        NetMgr.Instance.Send(ctsr);
    }
    private void OnRegisterRet(object obj)
    {
        MsgMgr.Instance.RemoveListener(typeof(S2CRegisterRet), OnRegisterRet);

        S2CRegisterRet stcr = obj as S2CRegisterRet;
        if (stcr.code == 0)
        {
            UIMgr.Instance.Show<TipView>("注册成功!");
        }
        else
        {
            UIMgr.Instance.Show<TipView>("注册失败!");
        }
    }

    private void OnBack()
    {
        Close();
        UIMgr.Instance.Show<LoginView>();
    }
}
